extends Control

@onready var health_bar = $HealthBar
@onready var delayed_bar = $DelayedBar
@export var tween_delay: float = 0.05      # 延迟开始动画的时间
@export var tween_duration: float = 0.25   # Tween 动画持续时间
var player = null

var tween_active: bool = false
var tween_active_health: bool = false

func _ready() -> void:
	#set_anchors_preset(Control.PRESET_TOP_LEFT)
	#offset_left = 0
	#offset_top = 0
	
	# 设置延迟血条颜色（如果想要纯白可改为 Color(1, 1, 1)）
	delayed_bar.tint_progress = Color(0.56, 0.67, 0.65)
	
	# 假设最大生命值为 100，设置血条最大值及初始值
	health_bar.max_value = 100
	delayed_bar.max_value = 100
	health_bar.value = 100
	delayed_bar.value = 100
	
	var current_scene = get_tree().get_current_scene()
	print("当前活动场景：", current_scene.name)
	_print_tree(current_scene)
	player = current_scene.get_node("Player")
	if player:
		print("找到 Player 节点：", player.name)
	else:
		print("没有找到 Player 节点，请检查节点路径")
		
	set_process(true)
	
	# 设置血条的层级
	var canvas_layer = get_parent()
	if canvas_layer is CanvasLayer:
		canvas_layer.layer = 1  # 确保血条在正确的层级
	
func _print_tree(node: Node, indent: int = 0) -> void:
	print(node.name)
	for child in node.get_children():
		_print_tree(child, indent + 1)
		
func _process(delta: float) -> void:
	if player:
		# 当 health_bar 的数值与 player's health 不一致时，用 Tween 平滑更新 health_bar
		if abs(health_bar.value - player.health) > 0.01 and not tween_active_health:
			tween_active_health = true
			var th = create_tween()
			th.tween_property(health_bar, "value", player.health, tween_duration).set_trans(Tween.TRANS_LINEAR).set_ease(Tween.EASE_IN_OUT)
			th.connect("finished", Callable(self, "_on_health_tween_finished"))
		
		# 延迟血条的动画逻辑
		if delayed_bar.value < health_bar.value:
			delayed_bar.value = health_bar.value
			tween_active = false
		elif delayed_bar.value > health_bar.value and not tween_active:
			tween_active = true
			var tw = create_tween()
			tw.tween_interval(tween_delay)
			tw.tween_property(delayed_bar, "value", health_bar.value, tween_duration).set_trans(Tween.TRANS_LINEAR).set_ease(Tween.EASE_IN_OUT)
			tw.connect("finished", Callable(self, "_on_tween_finished"))
		
func _on_tween_finished() -> void:
	tween_active = false
	
func _on_health_tween_finished() -> void:
	tween_active_health = false
